package com.tc.service.personalImpl;

import com.tc.client.ItemHome;
import com.tc.dto.Result;
import com.tc.factory.ResultFactory;
import com.tc.mapper.PersonalMapper;
import com.tc.myDto.BusinessInformation;
import com.tc.myDto.UserApp;
import com.tc.service.PersonalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.ExecutorService;

@Service
public class PersonalServiceImpl implements PersonalService {
    @Autowired
    private PersonalMapper personalMapper;
    @Autowired
    private ResultFactory result;
    @Autowired
    private ExecutorService executorService;
    @Autowired
    private ItemHome itemHome;

    //注册商家
    @Override
    @Transactional
    public Result addBusiness(BusinessInformation businessInformation, HttpServletRequest request) {
        //一个账号只能注册一个商家
        String id=request.getHeader("id");
        //首先判断该账号是否存在商家
        if(personalMapper.exist(id) != null){
            //能进来说明存在
            return result.error("只能创建一家店铺");
        }
        //接着判断店铺名有没有重复,通过feign客户端访问其他服务
        if(itemHome.checkShopName(businessInformation.getShopName()) != null) {
            //能进来说明店铺名重复了
            return result.error("店铺名已存在");
        }
        //能走到这说明符合创建店铺的条件
        executorService.submit(()->{
            businessInformation.setUserId(Integer.valueOf(id));
            //首先先添加此商家个人信息
            personalMapper.addShop(businessInformation);
            //然后获取新增店铺的主键id并与用户绑定
            personalMapper.bindingUser(
                    personalMapper.getNewShopId(businessInformation.getShopName()),Integer.valueOf(id)
            );
            //然后使用feign客户端给管理端注册此账户
            itemHome.addShop(businessInformation);
        });
        return result.success("success");
    }

    //修改用户信息
    @Override
    public Result updateUserApp(UserApp user) {
        //直接异步修改
        executorService.submit(()->
            personalMapper.updateUserApp(user)
        );
        return result.success("success");
    }

    //获取个人信息
    @Override
    public UserApp selectInformaion(Integer id) {
        return personalMapper.selectInformation(id);
    }

}
